package cn.dlc.com.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayParamFlowItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * sentinel限流配置类
 */
@Configuration
public class GatewayConfiguration {

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer){

        System.out.println("init GatewayConfiguration.....");

        this.serverCodecConfigurer = serverCodecConfigurer;
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    }

    /**
     * 配置限流的异常处理类
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler(){

        System.out.println("sentinelGatewayBlockExceptionHandler...");

        return new SentinelGatewayBlockExceptionHandler(viewResolvers,serverCodecConfigurer);
    }

    /**
     * 配置限流过滤器
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter(){

        System.out.println("sentinelGatewayFilter.....");

        return new SentinelGatewayFilter();
    }

    @PostConstruct
    public void initGatewayRules(){
        Set<GatewayFlowRule> rules = new HashSet<>();
        // 不分组的情况，使用这部分代码
//        rules.add(new GatewayFlowRule("product-server")
//                // 配置的是一秒一个请求
//                .setCount(1)
//                .setIntervalSec(1));

        // 分组之后对应这部分代码(参数和ApiDefinition中的参数一致)
        rules.add(new GatewayFlowRule("product-api")
                .setCount(1).setIntervalSec(1));

        rules.add(new GatewayFlowRule("order-api")
                .setCount(1).setIntervalSec(1)
                // 设置参数，添加了这个参数才有效果
                .setParamItem(new GatewayParamFlowItem()
                        .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
                        .setFieldName("id")));

        GatewayRuleManager.loadRules(rules);
    }

    // 通用异常处理类
    @PostConstruct
    public void initBlockHandler(){
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {

            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map<String,Object> map = new HashMap<>();
                map.put("code","001");
                map.put("msg","木鱼，你被限流了，你是不是傻..");

                // 返回提示信息
                return ServerResponse.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .body(BodyInserters.fromObject(map));
            }
        };
        // 默认是DefaultBlockRequestHandler
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    /**
     * 自定义api限流分组，这个地方就是分了两个组
     */
    @PostConstruct
    public void initCustomizeApis(){
        // 总的分组
        Set<ApiDefinition> definitions = new HashSet<>();

        // 针对product-server的分组，但是为什么要用hashset？
        Set<ApiPredicateItem> productItems = new HashSet<>();
        // ApiPredicateItem的子类
        ApiPathPredicateItem productItem = new ApiPathPredicateItem();
        productItem.setPattern("/product-server/**");
        // 以指定路径开头的匹配方式，如果不指定MatchStrategy的话表示完全匹配
        productItem.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX);
        productItems.add(productItem);
        ApiDefinition productApi = new ApiDefinition("product-api")
                .setPredicateItems(productItems);


        // 针对product-server的分组，但是为什么要用hashset？
        Set<ApiPredicateItem> orderItems = new HashSet<>();
        // ApiPredicateItem的子类
        ApiPathPredicateItem orderItem = new ApiPathPredicateItem();
        orderItem.setPattern("/order-server/**");
        orderItem.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX);
        orderItems.add(orderItem);
        ApiDefinition orderApi = new ApiDefinition("order-api")
                .setPredicateItems(orderItems);

        definitions.add(productApi);
        definitions.add(orderApi);
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }
}
